package lesson03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClinet02 {
    private Socket socket;
    private String ServerIp;
    private int Serverport;

    public TCPEchoClinet02(String serverIp, int serverport) throws IOException {
        if (serverIp == null || serverIp.isEmpty()) {
            throw new BindException("服务器ip不能为空");
        }
        if (serverport < 1024 || serverport > 65535) {
            throw new BindException("端口号需要在1024 - 65535之间");
        }
        // 这个类可以自动获取系统自动给客户端分配的ip与端口号，我们传入了服务器的ip与port也会保存
        // 所以socket里面存放了客户端与服务器的ip与端口号
        socket = new Socket(serverIp, serverport);
    }

    public void start() {
        System.out.println("客户端已启动.");
        //创建输入与输出流进行网卡的读写操作
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true){

                System.out.print("-> ");
                //1.创建一个写操作，让用户进行输入传入服务器
                Scanner scanner = new Scanner(System.in);
                String request = scanner.nextLine();//写一整行字符
                PrintWriter printWriter = new PrintWriter(outputStream);  // 创建PrintWriter类，方便进行写操作
                printWriter.println(request);  //将用户输入的数据发送到网卡
                printWriter.flush();     //将网卡中的数据发送到服务器段
                Scanner responseScanner = new Scanner(inputStream);
                String response = responseScanner.nextLine();
                System.out.printf("request = %s  response = %s \n", request, response);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClinet02 tcpEchoClinet02 = new TCPEchoClinet02("127.0.0.1", 9090);
        tcpEchoClinet02.start();
    }
}
